﻿using Kingdee.BOS;
using Kingdee.BOS.Core.CommonFilter;
using Kingdee.BOS.Core.CommonFilter.PlugIn;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.Core.Permission;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Kingdee.K3.SCM.ServiceHelper;
using System.Text;
using System.Threading.Tasks;
using static Kingdee.BOS.App.Core.Validation.EntryEntity.CompositePKValidator.KeyHelper;

namespace RK.FilterPlugin.CommonTest
{
    public class DzStockFilterCommon : AbstractCommonFilterPlugIn
    {
        protected List<long> lstStkOrg = new List<long>();
        protected string selOrgId = string.Empty;
        protected Dictionary<long, string> dctSelOrg = new Dictionary<long, string>();
        protected Dictionary<long, string> dctAllOrg = new Dictionary<long, string>();
        protected void SetDctSelOrgId()
        {
            dctSelOrg.Clear();
            if (selOrgId.Length != 0)
            {
                List<string> list = selOrgId.Split(',').ToList();
                foreach (string item in list)
                {
                    if (!dctSelOrg.ContainsKey(Convert.ToInt64(item)) && dctAllOrg.ContainsKey(Convert.ToInt64(item)))
                    {
                        dctSelOrg.Add(Convert.ToInt64(item), dctAllOrg[Convert.ToInt64(item)]);
                    }
                }
            }
        }
        protected void SetFilterGridMuliOrg(BeforeFilterGridF7SelectEventArgs e)
        {
            string text = string.Empty;
            switch (e.Key.ToUpperInvariant())
            {
                case "FMATERIALNUMBER":
                case "FMATERIALNAME":
                case "FMATERIALTYPENAME":
                case "FBOMID":
                case "FBOMNUMBER":
                case "FBOMNO":
                case "FSTOCKSTATUSNUMBER":
                case "FSTOCKSTATUSNAME":
                case "FSTOCKNUMBER":
                case "FSTOCKNAME":
                    if (CheckOrgList(e) && !CheckBaseDataShare(e.Key.ToUpperInvariant()))
                    {
                        text = $"  FUseOrgId IN ({selOrgId})";
                    }
                    break;
                case "FOWNERNUMBER":
                case "FOWNERNAME":
                    {
                        FilterRow val2 = e.CommonFilterModel.FilterObject.FilterRows.FirstOrDefault((FilterRow item) => StringUtils.EqualsIgnoreCase(item.FilterField.FieldName, "FOwnerTypeId"));
                        if (CheckOrgList(e) && val2 != null && !CheckBaseDataShare(val2.Value.ToUpperInvariant()))
                        {
                            text = $"  FUseOrgId IN ({selOrgId})";
                        }
                        break;
                    }
                case "FKEEPERNUMBER":
                case "FKEEPERNAME":
                    {
                        FilterRow val = e.CommonFilterModel.FilterObject.FilterRows.FirstOrDefault((FilterRow item) => StringUtils.EqualsIgnoreCase(item.FilterField.FieldName, "FKEEPERTYPEID"));
                        if (CheckOrgList(e) && val != null && !CheckBaseDataShare(val.Value.ToUpperInvariant()))
                        {
                            text = $"  FUseOrgId IN ({selOrgId})";
                        }
                        break;
                    }
                case "FCUSTRNAME":
                    if (CheckOrgList(e) && !CheckBaseDataShare("BD_CUSTOMER"))
                    {
                        text = $"  FUseOrgId IN ({selOrgId})";
                    }
                    break;
                case "FSUPPLIERNAME":
                    if (CheckOrgList(e) && !CheckBaseDataShare("BD_SUPPLIER"))
                    {
                        text = $"  FUseOrgId IN ({selOrgId})";
                    }
                    break;
            }
            if (!string.IsNullOrEmpty(text))
            {
                if (string.IsNullOrEmpty(e.ListFilterParameter.Filter))
                {
                    e.ListFilterParameter.Filter = (text);
                    return;
                }
                IRegularFilterParameter listFilterParameter = e.ListFilterParameter;
                listFilterParameter.Filter = (listFilterParameter.Filter + " AND " + text);
            }
        }

        private bool CheckBaseDataShare(string sKey)
        {
            bool result = true;
            string text = string.Empty;
            switch (sKey)
            {
                case "FMATERIALNUMBER":
                case "FMATERIALNAME":
                    text = "BD_MATERIAL";
                    break;
                case "FMATERIALTYPENAME":
                    text = "BD_MATERIALCATEGORY";
                    break;
                case "FSTOCKSTATUSNUMBER":
                case "FSTOCKSTATUSNAME":
                    text = "BD_StockStatus";
                    break;
                case "FSTOCKNUMBER":
                case "FSTOCKNAME":
                    text = "BD_STOCK";
                    break;
                case "FBOMID":
                case "FBOMNUMBER":
                case "FBOMNO":
                    text = "ENG_BOM";
                    break;
                case "BD_SUPPLIER":
                    text = "BD_Supplier";
                    break;
                case "BD_CUSTOMER":
                    text = "BD_Customer";
                    break;
            }
            if (!string.IsNullOrEmpty(text))
            {
                result = BDServiceHelper.IsBaseDataShare(this.Context, text);
            }
            return result;
        }

        private bool CheckOrgList(BeforeFilterGridF7SelectEventArgs e)
        {
            ListShowParameter val = e.DynamicFormShowParameter as ListShowParameter;
            if (val != null)
            {
                val.IsIsolationOrg = (false);
            }
            if (selOrgId.Trim().Length <= 0)
            {
                e.Cancel = (true);
                this.View.ShowMessage(ResManager.LoadKDString("请先选库存组织", "004024030002386", (SubSystemType)5, new object[0]), 0);
                return false;
            }
            return true;
        }

        protected void InitStkOrgId()
        {
            if (this.View.ParentFormView != null)
            {
                lstStkOrg = GetPermissionOrg(this.View.ParentFormView.BillBusinessInfo.GetForm().Id);
            }
            List<EnumItem> organization = GetOrganization(this.View.Context);
            ComboFieldEditor fieldEditor = this.View.GetFieldEditor<ComboFieldEditor>("FStockOrgId", 0);
            fieldEditor.SetComboItems(organization);
            lstStkOrg = new List<long>();
            foreach (EnumItem item in organization)
            {
                lstStkOrg.Add(Convert.ToInt64(item.Value));
            }
            object value = this.Model.GetValue("FStockOrgId");
            if (ObjectUtils.IsNullOrEmpty(value) && organization.Count((EnumItem p) => Convert.ToInt64(p.Value) == this.Context.CurrentOrganizationInfo.ID) > 0 && this.Context.CurrentOrganizationInfo.FunctionIds.Contains(103L))
            {
                this.View.Model.SetValue("FStockOrgId", Context.CurrentOrganizationInfo.ID);
                selOrgId = this.Context.CurrentOrganizationInfo.ID.ToString();
                if (!dctSelOrg.ContainsKey(this.Context.CurrentOrganizationInfo.ID))
                {
                    dctSelOrg.Add(this.Context.CurrentOrganizationInfo.ID, this.Context.CurrentOrganizationInfo.Name);
                }
            }
            if (!ObjectUtils.IsNullOrEmpty(value) && !string.Equals(selOrgId, value.ToString()))
            {
                selOrgId = value.ToString();
                SetDctSelOrgId();
            }
        }

        protected List<EnumItem> GetOrganization(Context context)
        {
            List<EnumItem> list = new List<EnumItem>();
            List<SelectorItemInfo> list2 = new List<SelectorItemInfo>();
            list2.Add(new SelectorItemInfo("FORGID"));
            list2.Add(new SelectorItemInfo("FNUMBER"));
            list2.Add(new SelectorItemInfo("FNAME"));
            string inFilter = GetInFilter("FORGID", lstStkOrg);
            inFilter += $" AND FORGFUNCTIONS LIKE '%{103L.ToString()}%' ";
            inFilter += GetOtherFilter();
            QueryBuilderParemeter val = new QueryBuilderParemeter();
            val.FormId = ("ORG_Organizations");
            val.SelectItems = (list2);
            val.FilterClauseWihtKey = (inFilter);
            val.OrderByClauseWihtKey = ("FNUMBER");
            QueryBuilderParemeter val2 = val;
            DynamicObjectCollection dynamicObjectCollection = QueryServiceHelper.GetDynamicObjectCollection(this.Context, val2, null);
            foreach (DynamicObject item in (Collection<DynamicObject>)(object)dynamicObjectCollection)
            {
                EnumItem val3 = new EnumItem((DynamicObject)(object)new DynamicObject(EnumItem.EnumItemType));
                val3.EnumId = item["FORGID"].ToString();
                val3.Value = (item["FORGID"].ToString());
                long key = (long)item["FORGID"];
                string text = (item["FName"] == null) ? "" : item["FName"].ToString();
                val3.Caption = ((LocaleValue)(object)new LocaleValue(string.Format("{0} {1}", (item["FNumber"] ?? "").ToString(), text), this.Context.UserLocale.LCID));
                list.Add(val3);
                if (!dctAllOrg.ContainsKey(key))
                {
                    dctAllOrg.Add(key, text);
                }
            }
            if (list.Count() == 0)
            {
                this.View.ShowMessage(ResManager.LoadKDString("库存组织未结束初始化，请先结束初始化！", "004024030002389", (SubSystemType)5, new object[0]), (MessageBoxOptions)0, "", (MessageBoxType)0);
            }
            return list;
        }

        private string GetOtherFilter()
        {
            return " AND EXISTS(SELECT 1 FROM T_BAS_SYSTEMPROFILE BSP \r\nWHERE BSP.FCATEGORY = 'STK' AND BSP.FACCOUNTBOOKID = 0 AND BSP.FORGID = FORGID \r\nAND BSP.FKEY = 'IsInvEndInitial' AND BSP.FVALUE = '1') ";
        }

        private string GetInFilter(string key, List<long> valList)
        {
            if (valList == null || valList.Count() == 0)
            {
                return $"{key} = -1 ";
            }
            return string.Format("{0} IN ({1})", key, string.Join(",", valList));
        }

        protected List<long> GetPermissionOrg(string formId)
        {
            string subSystemId = "21";
            if (this.View != null && this.View.ParentFormView != null)
            {
                if (this.View.ParentFormView.BillBusinessInfo != null)
                {
                    Form form = this.View.ParentFormView.BillBusinessInfo.GetForm();
                    if (form != null)
                    {
                        //这里给什么值 
                        form.SupportPermissionControl = 1;
                    }
                }
                if (this.View.ParentFormView.Model != null && !string.IsNullOrWhiteSpace(this.View.ParentFormView.Model.SubSytemId))
                {
                    subSystemId = this.View.ParentFormView.Model.SubSytemId;
                }
            }
            BusinessObject val = new BusinessObject();
            val.Id = formId;
            val.PermissionControl = (1);
            val.SubSystemId = (subSystemId);
            BusinessObject val2 = val;
            return PermissionServiceHelper.GetPermissionOrg(this.Context, val2, "6e44119a58cb4a8e86f6c385e14a17ad");
        }
    }
}
